package com.itheima.service;

import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserServiceTest {
    private SqlSession sqlSession;
    private UserMapper mapper;

    @Before
    public void init() throws IOException {
        // 加载核心配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");

        // 获取SqlSessionFactoryBuilder
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

        // 获取SqlSessionFactory
        SqlSessionFactory factory = builder.build(in);

        // 获取连接SqlSession
        sqlSession = factory.openSession();

        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void close() {
        // 提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
    }

    @Test
    public void findAll(){

        List<User> users = mapper.findAll();

        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void findById(){

        User user = mapper.findById(1);
        System.out.println(user);
    }

    @Test
    public void findCount(){
        int count = mapper.findCount();
        System.out.println("count = " + count);
    }

    @Test
    public void findByName(){
        List<User> users = mapper.findByName("张");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void addUser(){
        User user = new User(null,"钱七",21);
        mapper.addUser(user);
    }

    @Test
    public void updateUser(){
        User user = new User(1,"张三",25);
        mapper.updateUser(user);
    }

    @Test
    public void deleteUser(){
        mapper.deleteUser(11);
    }
}
